project('cli-tools', ['c', 'cpp'],
    version: '0.1',
    license: 'GPL-2.0',
    license_files: 'LICENSE',
    default_options: ['warning_level=3',],
)

install_dirs = {
    'linux': '/home/zzh/path',
    'windows': 'D:/Path',
    'cygwin': '/cygdrive/d/Path'
}

system_name = target_machine.system()
install_path = install_dirs[system_name]
build_dir = meson.current_build_dir()
src_dir = meson.current_source_dir()

message('install path:', install_path)

c_args = []
cpp_args = []
ld_args = []

fs = import('fs')

if 'linux' == system_name

c_find_res = run_command('find', './', '-maxdepth', '1', '-regex', '.*\.c',
    capture: true,
    check: false
)

cpp_find_res = run_command('find', './', '-maxdepth', '1', '-regex', '.*\.cpp',
    capture: true,
    check: false
)

elif 'cygwin' == system_name or 'windows' == system_name

c_find_res = run_command('ls', '*.c',
    capture: true,
    check: false
)

cpp_find_res = run_command('ls', '*.cpp',
    capture: true,
    check: false
)

endif

c_srcs = c_find_res.stdout().split('\n')
cpp_srcs = cpp_find_res.stdout().split('\n')

lib_srcs = [
    'lib/common.c'
]

incs = ['lib']

lib = shared_library('cmdtool_common', lib_srcs,
    install: true,
    install_dir: install_path
)

# all_srcs = c_srcs + cpp_srcs

all_srcs = []

foreach src : c_srcs
    if '' != src
        all_srcs += src
    endif
endforeach

build_setup = {
    'debug': {
        # 'suffix': true,
        'c_args': [
            '-g3',
            '-O0'
        ]
    },
    'release': {
        'suffix': '',
        'c_args': [
            '-O2'
        ],
        'install': true
    }
}

install_list = []

foreach setup_name, options: build_setup

    foreach src : all_srcs

        exe_name = fs.stem(src)
        suffix = options.get('suffix', setup_name)

        if '' != suffix
            exe_name += '_' + suffix
        endif

        install = options.get('install', false)

        exe = executable(exe_name, src,
            include_directories: incs,
            c_args: c_args + options.get('c_args', []),
            cpp_args: cpp_args + options.get('cpp_args', []),
            link_args: ld_args + options.get('ld_args', []),
            link_with: lib,
            install: install,
            install_dir: install_path
        )

        if true == install
            install_list += exe
        endif

    endforeach

endforeach

file_list = [lib.full_path()]

foreach exe: install_list
    file_list += exe.full_path()
endforeach

run_target('install_custom',
    command: [
        'cp',
        file_list,
        install_path
    ]
)
